package com.car.order.consumer;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.car.commons.core.model.Result;
import com.car.commons.core.model.WoniuException;
import com.car.commons.web.util.StateUtil;
import com.car.order.client.CarShoppingClient;
import com.car.order.dto.alipay.PayInfoDto;
import com.car.order.dto.goodOrderInfo.GoodsInfoDetail;
import com.car.order.dto.goods.GoodsDto;
import com.car.order.entity.GoodOrderInfo;
import com.car.order.entity.GoodOrderItem;
import com.car.order.entity.GoodOrderLog;
import com.car.order.mapper.GoodOrderInfoMapper;
import com.car.order.mapper.GoodOrderItemMapper;
import com.car.order.service.GoodOrderLogService;
import com.car.order.util.AlipayUtil;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@RabbitListener(queues = "goods_order_check_queue")
public class CheckGoodsOrderConsumer {
    @Autowired
    private AlipayUtil alipayUtil;
    @Autowired
    private GoodOrderInfoMapper goodOrderInfoMapper;
    @Autowired
    private GoodOrderItemMapper goodOrderItemMapper;
    @Autowired
    private CarShoppingClient carShoppingClient;
    @Resource
    private GoodOrderLogService goodOrderLogService;


    @RabbitHandler
    public void handler(String orderNum) throws Exception {
        PayInfoDto payInfoDto = alipayUtil.queryPayState(orderNum);
        GoodOrderInfo orderInfo = goodOrderInfoMapper.selectById(orderNum);
        QueryWrapper<GoodOrderItem> w = new QueryWrapper<>();
//        w.eq("order_id", orderInfo.getGoodOrderId());
//        List<GoodOrderItem> goodOrderItems = goodOrderItemMapper.selectList(w);
        List<GoodsInfoDetail> orderDetail = orderInfo.getOrderDetail();
        Set<GoodsDto> goodsDtos = BeanUtil.copyToList(orderDetail, GoodsDto.class).stream().collect(Collectors.toSet());
        if (payInfoDto.getPayState().equals("TRADE_SUCCESS")) {
            if (orderInfo.getOrderState().equals(StateUtil.GOODS_STATE_NOMAL)) {
                //修改冻结量
                Result result = carShoppingClient.reduceFreezeStock(goodsDtos);
                if (result.getCode() != 200) {
                    throw new WoniuException(result.getCode(), result.getMsg());
                }
                //修改订单状态
                orderInfo.setOrderState(StateUtil.GOODS_ORDER_STATE_NOT_RECEIVED);
                //支付时间
                LocalDateTime localDateTime = LocalDateTime.parse(payInfoDto.getPayDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                orderInfo.setOrderPayTime(localDateTime.toString());
                goodOrderInfoMapper.updateById(orderInfo);
                //生成日志
                GoodOrderLog goodOrderLog = new GoodOrderLog();
                goodOrderLog.setGoodOrderId(orderNum);
                goodOrderLog.setLogDesc("用户完成订单支付");
                goodOrderLog.setLogTime(localDateTime.toString());
                goodOrderLogService.save(goodOrderLog);
            }
        } else {//未支付
            if (orderInfo.getOrderState().equals(StateUtil.GOODS_ORDER_STATE_UNPAID)) {
                orderInfo.setOrderState(StateUtil.GOODS_ORDER_STATE_CANCELLED);
                goodOrderInfoMapper.updateById(orderInfo);
                //修改冻结量和库存量
                Result result = carShoppingClient.addStockAndReduceFreezeStock(goodsDtos);
                if (result.getCode() != 200) {
                    throw new WoniuException(result.getCode(), result.getMsg());
                }
                //生成日志
                GoodOrderLog goodOrderLog = new GoodOrderLog();
                goodOrderLog.setGoodOrderId(orderNum);
                goodOrderLog.setLogDesc("订单超时，自动取消");
                LocalDateTime localDateTime = LocalDateTime.parse(payInfoDto.getPayDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                goodOrderLog.setLogTime(localDateTime.toString());
                goodOrderLogService.save(goodOrderLog);
            }
        }
    }
}
